package cn.edu.fzu.homemaking.chat.filter;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import cn.edu.fzu.homemaking.chat.api.SsoApi;
import cn.edu.fzu.homemaking.common.SessionConstant;
import cn.edu.fzu.homemaking.web.Result;
import cn.edu.fzu.homemaking.web.RetCode;

@WebFilter(urlPatterns = "/api/chat/*")
public class AuthFilter implements Filter {

    @Resource
    private SsoApi ssoApi;

    @Override
    public void init(FilterConfig filterConfig) {
    }


    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        HttpSession session = req.getSession();

        //判断是否登陆
        Result login = ssoApi.isLogin();
        if (login.getCode() != RetCode.SUCCESS) {
            //返回前端登陆报错信息，比如账号被异地登陆踢出
            respWriter(resp, new Result(RetCode.REFUSE_LOGIN, null, login.getMessage(), null));
            return;
        }
        //如果没有登陆
        if (!(boolean) login.getValue()) {
            //返回登陆页面给前端
            String loginUrl = (String) ssoApi.loginIndex(null).getValue();
            respWriter(resp, new Result(RetCode.NO_LOGIN, null, null, loginUrl));
            return;
        }

        String origin = (String) ssoApi.getSession(SessionConstant.USER_TYPE).getValue();
        session.setAttribute(SessionConstant.USER_TYPE, origin);

        Result result = ssoApi.getSession(SessionConstant.ACCOUNT);
        JSONObject user = (JSONObject) JSONObject.toJSON(result.getValue());
        Long userId = null;
        if (SessionConstant.USER.equals(origin)) {
            userId = user.getLong("customerId");
        } else if (SessionConstant.COMPANY.equals(origin)) {
            userId = user.getJSONObject("company").getLong("id");
        }
        session.setAttribute(SessionConstant.USER_ID, userId);
        chain.doFilter(req, resp);
    }


    @Override
    public void destroy() {
        // do nothing
    }


    private void respWriter(HttpServletResponse resp, Result result) throws IOException {
        resp.getWriter().print(JSON.toJSONString(result));
    }

}
